package org.chen.aao.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.chen.aao.app.mapper.AppVersionMapper;
import org.chen.aao.app.service.AppVersionService;
import org.chen.aao.app.utils.VersionUtil;
import org.chen.aao.common.app.AppVersion;
import org.chen.aao.common.app.dto.AppVersionCheckRequest;
import org.chen.aao.common.app.dto.AppVersionCheckResponse;
import org.springframework.stereotype.Service;

/**
 * APP版本服务实现类
 */
@Slf4j
@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService {
    
    @Override
    public AppVersionCheckResponse checkVersion(AppVersionCheckRequest request) {
        // 查询对应平台的最新版本信息
        LambdaQueryWrapper<AppVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppVersion::getPlatform, request.getPlatform().toLowerCase())
               .eq(AppVersion::getEnabled, true)
               .orderByDesc(AppVersion::getId)
               .last("LIMIT 1");
        
        AppVersion appVersion = this.getOne(wrapper);
        
        if (appVersion == null) {
            log.warn("未找到平台 {} 的版本信息", request.getPlatform());
            return null;
        }
        
        // 构建响应对象
        AppVersionCheckResponse response = new AppVersionCheckResponse();
        response.setLatestVersion(appVersion.getLatestVersion());
        response.setMinimumVersion(appVersion.getMinimumVersion());
        response.setUpdateUrl(appVersion.getUpdateUrl());
        response.setReleaseNotes(appVersion.getReleaseNotes());
        
        // 判断是否需要强制更新
        boolean needForceUpdate = checkNeedForceUpdate(
            request.getVersion(), 
            appVersion.getMinimumVersion(), 
            appVersion.getLatestVersion()
        );
        
        response.setForceUpdate(needForceUpdate || appVersion.getForceUpdate());
        
        log.info("版本检查 - 平台: {}, 当前版本: {}, 最新版本: {}, 强制更新: {}", 
                request.getPlatform(), 
                request.getVersion(), 
                appVersion.getLatestVersion(), 
                response.getForceUpdate());
        
        return response;
    }

    /**
     * 检查是否需要强制更新
     * @param currentVersion 当前版本
     * @param minimumVersion 最低支持版本
     * @param latestVersion 最新版本
     * @return 是否需要强制更新
     */
    private boolean checkNeedForceUpdate(String currentVersion, String minimumVersion, String latestVersion) {
        // 如果当前版本低于最低支持版本，则需要强制更新
        return VersionUtil.compareVersion(currentVersion, minimumVersion) < 0;
    }
}